package com.base.look.act;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.bean.StatEntity;
import com.base.commonlib.utils.GlideUtil;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.SubStringUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.look.R;
import com.base.look.adapter.GridImageAdapter;
import com.base.look.bean.AddLookBean;
import com.base.look.bean.LocationCheckedEntity;
import com.base.look.bean.StatEntity2;
import com.base.look.databinding.ActivityEditLookBinding;
import com.base.look.fragment.LookFragment;
import com.base.look.presenter.EditLookPresenter;
import com.base.look.utils.CaremaPhotoUtils;
import com.base.look.view.EditLookView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

@Route(path = "/look/editlook")
public class EditLookActivity extends CBaseBarMvpActivity<EditLookPresenter> implements EditLookView {

    private ActivityEditLookBinding mBinding;
    private List<LocalMedia> selectList = new ArrayList<>();
    private Disposable disposable;
    @Autowired
    public String images;
    private GridImageAdapter adapter;
    private int maxSelectNum = 9;
    private SelectPopupWindow selectPopupWindow;

    @Autowired
    public String type;// 1 只编辑文字  3 分享过来的新闻
    @Autowired
    public String url;// 1 只编辑文字  3 分享过来的新闻
    @Autowired
    public String courseId;// 分享id
    @Autowired
    public String title;// 分享过来的新闻标题
    @Autowired
    public String imgurl;// 分享过来的新闻标题

    private int photo = 0;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_edit_look;
    }

    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityEditLookBinding) mRootBinding;
        mPresenter = new EditLookPresenter(this, this);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(mContext, 4, GridLayoutManager.VERTICAL, false);
        mBinding.recycler.setLayoutManager(manager);
        adapter = new GridImageAdapter(mContext, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mBinding.recycler.setAdapter(adapter);

        mBinding.relCLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/look/location_poi").navigation();
            }
        });
    }

    @Override
    protected void start() {
        setBackNavigation();
        mBinding.title.setText("发表内容");
        if ("2".equals(type)) {
            mBinding.linIsShowRecy.setVisibility(View.VISIBLE);
            try {
                JSONArray jsonArray = new JSONArray(images);
                for (int i = 0; i < jsonArray.length(); i++) {
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setChecked(jsonArray.getJSONObject(i).optBoolean("isChecked"));
                    localMedia.setCompressed(jsonArray.getJSONObject(i).optBoolean("compressed"));
                    localMedia.setCompressPath(jsonArray.getJSONObject(i).optString("compressPath"));
                    localMedia.setCut(jsonArray.getJSONObject(i).optBoolean("isCut"));
                    localMedia.setDuration(jsonArray.getJSONObject(i).optLong("duration"));
                    localMedia.setHeight(jsonArray.getJSONObject(i).optInt("height"));
                    localMedia.setWidth(jsonArray.getJSONObject(i).optInt("width"));
                    localMedia.setMimeType(jsonArray.getJSONObject(i).optInt("mimeType"));
                    localMedia.setNum(jsonArray.getJSONObject(i).optInt("num"));
                    localMedia.setPath(jsonArray.getJSONObject(i).optString("path"));
                    localMedia.setCutPath(jsonArray.getJSONObject(i).optString("cutPath"));
                    localMedia.setPictureType(jsonArray.getJSONObject(i).optString("pictureType"));
                    localMedia.setPosition(jsonArray.getJSONObject(i).optInt("position"));
                    selectList.add(localMedia);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            adapter.setList(selectList);
            adapter.notifyDataSetChanged();
            adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position, View v) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片
                            PictureSelector.create(EditLookActivity.this).themeStyle(R.style.picture_white_style).openExternalPreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(EditLookActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(EditLookActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            });
        } else if ("1".equals(type)) {
            //只发布文字
            mBinding.linIsShowRecy.setVisibility(View.GONE);
        }
        else if ("8".equals(type)) {
            //都可以
            mBinding.linIsShowRecy.setVisibility(View.VISIBLE);
        }
        else if ("3".equals(type)) {
            //分享来的新闻
            mBinding.linIsShowRecy.setVisibility(View.GONE);
            mBinding.linIsShowWeb.setVisibility(View.VISIBLE);
            mBinding.tvNewsTitle.setText(SubStringUtil.subStringCN(title, 30));
            mBinding.tvNewsTitle.setTag(url);
            GlideUtil.load(mContext,imgurl,mBinding.tvNewsImg);
            mBinding.linIsShowWeb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ARouter.getInstance().build("/home/homenew")
                            .withString("title", title)
                            .withString("id", courseId)
                            .navigation();
                }
            });
        }

//        mBinding.buttom.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ARouter.getInstance().build("/look/select_img_video").navigation();
//            }
//        });


        setRigTv("发表", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mBinding.editContent.getText().toString())) {
                    ToastUtil.show("内容不能为空！");
                    return;
                }
                List<String> ls = new ArrayList<>();
                if (selectList.size() > 0) {
                    for (int i = 0; i < selectList.size(); i++) {
                        ls.add(selectList.get(i).getPath());
                    }
                }
                AddLookBean addLookBean = new AddLookBean();
                addLookBean.setCourseId(courseId);
                addLookBean.setContent(mBinding.editContent.getText().toString().trim());
                if ("null".equals(locationCheckedEntity.getAddress()) || locationCheckedEntity.getAddress() == null) {
                    addLookBean.setAddress("");
                } else {
                    addLookBean.setAddress(locationCheckedEntity.getAddress());
                }

                addLookBean.setLatitude(String.valueOf(locationCheckedEntity.getLatitude()));
                addLookBean.setLongitude(String.valueOf(locationCheckedEntity.getLonTitude()));
                mPresenter.addLook2(ls, addLookBean);
            }
        });

//
//        mBinding.addPic.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//            }
//        });


        disposable = RxBus2.getInstance().doSubscribe(LocationCheckedEntity.class, new Consumer<LocationCheckedEntity>() {
            @Override
            public void accept(LocationCheckedEntity bean) throws Exception {
                locationCheckedEntity = bean;
                if (locationCheckedEntity.getState() == 0x00000101) {
                    mBinding.ivEditLocation.setImageResource(R.mipmap.icon_checked_location);
                    mBinding.location.setText(locationCheckedEntity.getAddress());
                    mBinding.location.setTextColor(Color.parseColor("#0278e9"));
                } else if (locationCheckedEntity.getState() == 0x00000102) {
                    mBinding.ivEditLocation.setImageResource(R.mipmap.icon_location);
                    mBinding.location.setText("所在位置");
                    mBinding.location.setTextColor(Color.parseColor("#333333"));
                }
            }
        });



//        mBinding.relCPhoto.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                CaremaPhotoUtils.goCarema(EditLookActivity.this, selectList, PictureMimeType.ofImage());
//            }
//        });
    }

    LocationCheckedEntity locationCheckedEntity = new LocationCheckedEntity();
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {

            selectPopupWindow = new SelectPopupWindow(mContext);
            selectPopupWindow.showAsDropDown(mBinding.recycler);
            if (selectList.size() > 0) {
                int pictureType = PictureMimeType.isPictureType(selectList.get(0).getPictureType());
                if (pictureType == PictureConfig.TYPE_IMAGE) {
                    if (selectPopupWindow != null) {
                        selectPopupWindow.setHidePVideoButton(View.GONE);
                    } else {
                        selectPopupWindow.setHidePVideoButton(View.VISIBLE);
                    }
                }
            }
            selectPopupWindow.setOnItemClickListener(new SelectPopupWindow.OnItemClickListener() {

                @Override
                public void onItemClick(int positon) {
                    switch (positon) {
                        //拍照、录视频
                        case 0:
                            //goCarema(PictureMimeType.ofImage());
                            CaremaPhotoUtils.goCarema(EditLookActivity.this, selectList, PictureMimeType.ofImage());
                            break;
                        //录视频
                        case 1:
                            //goCarema(PictureMimeType.ofVideo());
                            CaremaPhotoUtils.goCarema(EditLookActivity.this, selectList, PictureMimeType.ofVideo());
                            break;
                        //相册
                        case 2:
                            //goPhotos();
                            CaremaPhotoUtils.goPhotos(EditLookActivity.this, selectList);
                            break;
                    }
                }
            });

        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
//                    for (LocalMedia media : selectList) {
//                        Log.i("图片---getPath--》", media.getPath());
//                        Log.i("图片---getCompressPath--》", media.getCompressPath());
//                        Log.i("图片---getCutPath--》", media.getCutPath());
//                    }

                    if (selectList.size() > 0) {
                        int pictureType = PictureMimeType.isPictureType(selectList.get(0).getPictureType());
                        if (pictureType == PictureConfig.TYPE_IMAGE) {
                            if (selectPopupWindow != null) {
                                selectPopupWindow.setHidePVideoButton(View.GONE);
                            } else {
                                selectPopupWindow.setHidePVideoButton(View.VISIBLE);
                            }
                        }
                    }
                    mBinding.linIsShowRecy.setVisibility(View.VISIBLE);
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }


    @Override
    public void returnAddLookSuccess(String msg) {
        //包括裁剪和压缩后的缓存，要在上传成功后调用，注意：需要系统sd卡权限
        PictureFileUtils.deleteCacheDirFile(mContext);
        RxBus2.getInstance().post(new StatEntity2(0X0000010));
        ToastUtil.show(msg);
        finish();
    }

    @Override
    public void returnAddLookError() {
        ToastUtil.show("错误");
    }


}
